"""add first_timestamp field to LastAlert

Revision ID: c6e5594c99f8
Revises: bdae8684d0b4
Create Date: 2024-12-02 20:42:33.311541

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy import text
from sqlalchemy.dialects import mysql
from sqlalchemy.orm import Session

# revision identifiers, used by Alembic.
revision = "c6e5594c99f8"
down_revision = "bdae8684d0b4"
branch_labels = None
depends_on = None


def populate_db():
    session = Session(op.get_bind())

    session.execute(
        text(
            """
        UPDATE lastalert
        SET first_timestamp = (
            SELECT MIN(alert.timestamp)
            FROM alert
            WHERE alert.fingerprint = lastalert.fingerprint
            AND alert.tenant_id = lastalert.tenant_id
        )
    """
        )
    )


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    with op.batch_alter_table("incident", schema=None) as batch_op:
        batch_op.alter_column(
            "fingerprint",
            existing_type=mysql.TINYTEXT(),
            type_=sa.TEXT(),
            existing_nullable=True,
        )

    with op.batch_alter_table("lastalert", schema=None) as batch_op:
        batch_op.add_column(sa.Column("first_timestamp", sa.DateTime(), nullable=True))
        batch_op.create_index(
            batch_op.f("ix_lastalert_first_timestamp"),
            ["first_timestamp"],
            unique=False,
        )

    populate_db()


def downgrade() -> None:

    with op.batch_alter_table("lastalert", schema=None) as batch_op:
        batch_op.drop_index(batch_op.f("ix_lastalert_first_timestamp"))
        batch_op.drop_column("first_timestamp")
